package com.cskaoyan.exceptionhandler;

import com.cskaoyan.bean.Log;
import com.cskaoyan.mapper.LogMapper;
import com.cskaoyan.vo.BaseRespVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;


@ControllerAdvice
public class ShiroExceptionHandler {

    @Autowired
    LogMapper logMapper;

    @ExceptionHandler(value = UnauthorizedException.class)
    @ResponseBody
    public BaseRespVo unauthorizedException(Exception e, HttpServletRequest request) {

        //将权限行为写在日志
        String requestURI = request.getRequestURI();
        String remoteAddr = request.getRemoteAddr();

        Subject subject = SecurityUtils.getSubject();
        String username = (String) subject.getPrincipal();

        Date date = new Date(System.currentTimeMillis());
        date.setHours(date.getHours() + 8);

        Log log = new Log();
        log.setAdmin(username);
        log.setAction("访问：" + requestURI);
        log.setResult("没有权限！");
        log.setDeleted(false);
        log.setStatus(false);
        log.setType(3);
        log.setAddTime(date);
        log.setUpdateTime(date);
        log.setIp(remoteAddr);

        logMapper.insert(log);

        return BaseRespVo.error("对不起，你没有访问权限！");
    }

    @ExceptionHandler(value = AuthenticationException.class)
    @ResponseBody
    public BaseRespVo authenticationException(Exception e) {


        return BaseRespVo.error("登录失败！用户名密码错误！");
    }


}